//
//  SweepViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/24.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "SweepViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "EndSweepViewController.h"
//#import <>
@interface SweepViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) UIView *viewPreview;
@property (nonatomic, strong) UILabel *lbStatus;
@property (nonatomic, strong) UIBarButtonItem *startButton;

@property (nonatomic, strong) UIView *boxView;
@property (nonatomic, strong) CALayer *scanLayer;
- (BOOL)startReading;
- (void)stopReading;
//捕捉会话
@property (nonatomic, strong) AVCaptureSession *captureSession;
//展示layer
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;
@property (nonatomic, strong) NSString *url;
//
@property (nonatomic, strong) UILabel *Label;


//
@property (nonatomic, strong) UILabel *alertLabel;
@end

@implementation SweepViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"二维码";
    
    CGFloat height = kHeight - 64 - 49;
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake((kWidth - 50) / 2, height/ 3 - 80, 50, 50)];
    imageV.image = [UIImage imageNamed:@"礼物盒.png"];
    [self.view addSubview:imageV];
    
    UILabel *urlLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, height - height / 3 * 2 - 30, 50, 50)];
    urlLabel.text = @"网址:";
    urlLabel.textColor = [UIColor grayColor];
    [self.view addSubview:urlLabel];
    
    self.Label = [[UILabel alloc] initWithFrame:CGRectMake(10, height - height / 3 * 2 + 10, kWidth - 10 * 2, 30)];
    self.Label.numberOfLines = 0;
    self.Label.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:self.Label];
    
    UILabel *alertL = [[UILabel alloc] initWithFrame:CGRectMake(10, height - height / 3, kWidth - 10 * 2, 60)];
    alertL.text = @"该信息并非本软件提供,请谨慎使用,同时要注意保护你的隐私";
    alertL.textColor = [UIColor grayColor];
    alertL.numberOfLines = 0;
    alertL.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:alertL];
    
    _viewPreview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 143)];
    [self.view addSubview:_viewPreview];
    
    UIButton *requestB = [UIButton buttonWithType:UIButtonTypeSystem];
    requestB.frame = CGRectMake(20, height - height / 3 + 60, kWidth - 20 * 2, 25);
    [requestB setTitle:@"使用浏览器访问" forState:UIControlStateNormal];
    requestB.layer.masksToBounds = YES;
    requestB.layer.cornerRadius = 15;
    requestB.layer.borderWidth = 1;
    requestB.layer.borderColor = [UIColor colorWithWhite:0.72 alpha:0.9].CGColor;
    [requestB setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [requestB addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_viewPreview addSubview:requestB];
    
    self.alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth / 2 - 150, kHeight - 143, 300, 30)];
    self.alertLabel.textAlignment = NSTextAlignmentCenter;
    self.alertLabel.text = @"将二维码放入框内,即可自动扫描";
    [self.view addSubview:self.alertLabel];
    
    _startButton = [[UIBarButtonItem alloc] initWithTitle:@"再扫一次" style:(UIBarButtonItemStylePlain) target:self action:@selector(actionButton:)];
    self.navigationItem.rightBarButtonItem = _startButton;
    
    [self startReading];
    _captureSession = nil;
}
- (void)buttonClick:(UIButton *)button{
    //调用系统浏览器
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.Label.text]];
}
- (void)actionButton:(UIBarButtonItem *)rightButton{
    self.alertLabel.text = @"将二维码放入框内,即可自动扫描";
    [self startReading];
}
//实现startReading方法
- (BOOL)startReading{
    NSError *error;
    //1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //2.用CaptureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@",[error localizedDescription]);
        return NO;
    }
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *ouput = [[AVCaptureMetadataOutput alloc] init];
    //4.实例化捕捉会话
    _captureSession = [[AVCaptureSession alloc] init];
    //4.1.将输入流添加到会话
    [_captureSession addInput:input];
    //4.2.将媒体输出流添加到会话中
    [_captureSession addOutput:ouput];
    //5.创建串行队列,并将媒体输出流添加到队列当中
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [ouput setMetadataObjectsDelegate:self queue:dispatchQueue];
    //5.2.设置输出媒体数据类型为QRCode[设置扫码支持的编码格式（如下设置条形码和二维码兼容）]
    [ouput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    //ouput.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode128Code];
    //6.实例化预览图层
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    //7.设置预览图层填充方式
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //8.设置图层的frame
    [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
    
    //9.将图层添加到预览view的图层上
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    
    //10.设置扫描范围
    ouput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
    
    //10.1.扫描框
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height * 0.2f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.4f)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 1.0f;
    
    [_viewPreview addSubview:_boxView];
    
    //10.2.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    [timer fire];//启动定时器
    
    
    
    //10.开始扫描
    [_captureSession startRunning];
    return YES;
}
- (void)moveScanLayer:(NSTimer *)timer{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
        _scanLayer.frame = frame;
    }else{
        
        frame.origin.y += 5;
        
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}
//实现AVCaptureMetadataOutputObjectsDelegate协议方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //判断回传的数据类型
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            
            [_Label performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            [_alertLabel performSelectorOnMainThread:@selector(setText:) withObject:@"" waitUntilDone:NO];
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            _boxView.layer.borderColor = [UIColor clearColor].CGColor;
        }
    }
}

-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}



@end
